/*
 * @(#)UserAddAction.java 创建于 2014年3月14日 
 * 
 * Copyright (c) 2013-2014 by Drow.  
 *
 */
package com.hangxin.basic.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hangxin.basic.model.Company;
import com.hangxin.basic.model.LoginInfo;
import com.hangxin.basic.service.CompanyService;
import com.hangxin.basic.service.DictInfoService;
import com.hangxin.basic.service.UserService;
import com.hangxin.basic.util.Content;
import com.hangxin.commons.util.MD5Util;
import com.hangxin.commons.util.PageModel;
import com.hangxin.commons.web.BasicAction;
import com.hangxin.system.model.Syslog;
import com.hangxin.system.service.SyslogService;

@Controller
public class UserAction extends BasicAction
{
	static final Logger logger = LoggerFactory.getLogger(CompanyAction.class);
	@Resource
	private UserService userServiceImpl;// 添加登录用户service接口实现

	@Resource
	private CompanyService companyServiceImpl;// 组织结构Service

	@Resource
	private DictInfoService dictInfoServiceImpl;// role数据字典Service

	@Resource
	private SyslogService syslogServiceImpl;// 系统日志操作的Service

	/**
	 * 
	 * 功能描述：用户管理
	 * <P/>
	 * 创建时间：2014年3月17日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param pageno
	 * @param pages
	 * @param orgid
	 * @param model
	 * @return
	 */
	@RequestMapping(value="userManageAction")
	public String userManageAction(HttpServletRequest request, Integer pageno, Integer pages,Integer flag, String username, String realname, Integer state, Model model)
	{
		Boolean bool = false;
		pageno=(pageno==null)?1:pageno;
		pages=(pages==null)?1:pages;
		state=(state==null)?1:state;
		username=(username==null)?"":username;
		realname=(realname==null)?"":realname;
		
		PageModel p=new PageModel();
		p.setPages(pages);p.setPageNo(pageno);p.setPageSize(9);
		PageModel<Map<String, Object>> pageModel = userServiceImpl.getAllUser(p,  username, realname, state.intValue());
		model.addAttribute("pageModel", pageModel);
		model.addAttribute("username", username);
		model.addAttribute("realname", realname);
		model.addAttribute("state", state);
		flag=null;
		return "system/user/userManage";
	}
	
	/**
	 * 添加用户初始化
	 * @param request
	 * @param model
	 * @return
	 */
	
	@RequestMapping(value="userAddAction0")
	public String userAddAction0(HttpServletRequest request, Model model)
	{
		List<Map<String, Object>> list=companyServiceImpl.companyFind();
		model.addAttribute("list", list);
		return "system/user/userAdd";
	}

	/**
	 * 
	 * 功能描述：添加登录用户action
	 * <P/>
	 * 创建时间：2014年3月17日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param username
	 * @param employeeid
	 * @param companyid
	 * @param model
	 * @return
	 */
	@RequestMapping(value="userAddAction1")
	public void userAddAction1(HttpServletResponse response, HttpServletRequest request,LoginInfo logininfo, Model model, HttpSession session)
	{
		List<Integer> list=new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			if (userServiceImpl.checkName(logininfo.getUserName()) > 0)
			{
				list.add(2);
			} else
			{
				Long applicant = (Long) request.getSession().getAttribute("lgid");
				logininfo.setApplicant(applicant);
				userServiceImpl.userAdd(logininfo);
				list.add(1);
			}
			//添加系统操作日志
			StringBuffer content = new StringBuffer();
			content.append("用户：");
			content.append(request.getSession().getAttribute("realname"));
			content.append("，于");
			content.append(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format((new Date().getTime())));
			content.append("添加登录用户");
			content.append(logininfo.getUserName()+"("+logininfo.getRealName()+")");
			Syslog syslog = new Syslog(Long.valueOf(request.getSession().getAttribute("lgid").toString()), request.getSession().getAttribute("realname").toString(), request.getSession().getAttribute("companyname").toString(), "添加", "用户添加", content.toString(), Long.parseLong(request.getSession().getAttribute("lgid").toString()));
			syslog.setAddtime(new Timestamp(new Date().getTime()));
			syslogServiceImpl.save(syslog);// 添加操作日志
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
		
	}

	/**
	 * 
	 * 功能描述：添加登录用户时验证用户名是否已经存在
	 * <P/>
	 * 创建时间：2014年3月17日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param response
	 * @return
	 */
	@RequestMapping(value="userCheckAction")
	public Object userCheckAction(HttpServletResponse response, String username)
	{
		PrintWriter printWriter = null;
		try
		{
			printWriter = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (userServiceImpl.checkName(username) > 0)
		{
			printWriter.print("false");
		} else
		{
			printWriter.print("true");
		}
		return null;
	}



	/**
	 * 
	 * 功能描述：启用登录用户
	 * <P/>
	 * 创建时间：2014年3月19日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param state
	 * @param employee_id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="userForAction")
	public void userForAction(HttpServletResponse response, HttpServletRequest request,Integer state, Long id, Model model)
	{
		List<Integer> list = new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			if(userServiceImpl.userFor(state, id)>0){
				list.add(1);
			}
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
		
	}



	/**
	 * 
	 * 功能描述：根据id查找登录用户
	 * <P/>
	 * 创建时间：2014年3月19日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param state
	 * @param employee_id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="userFindAction")
	public String userFindAction(HttpServletResponse response, HttpServletRequest request, Long id, Integer orgid, Integer pageno, Integer pages, Model model)
	{

		Map<String, Object> logininfo = userServiceImpl.findUser(id);
		List<Map<String, Object>> list=companyServiceImpl.companyFind();
		model.addAttribute("list", list);
		model.addAttribute("map", logininfo);
		return "system/user/userEdit";
	}
	


	/**
	 * 
	 * 功能描述：根据id修改登录用户
	 * <P/>
	 * 创建时间：2014年3月20日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param state
	 * @param employee_id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="userEditAction")
	public void userEditAction(HttpServletResponse response, HttpServletRequest request, LoginInfo loginInfo, Integer pageno, Integer pages, Model model)
	{
		List<Integer> list = new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			userServiceImpl.editUser(loginInfo);
			list.add(1);
			//添加系统操作日志
			StringBuffer content = new StringBuffer();
			content.append("用户：");
			content.append(request.getSession().getAttribute("realname"));
			content.append("，于");
			content.append(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format((new Date().getTime())));
			content.append("修改登录用户");
			Syslog syslog = new Syslog(Long.valueOf(request.getSession().getAttribute("lgid").toString()), request.getSession().getAttribute("realname").toString(), request.getSession().getAttribute("companyname").toString(), "修改", "用户修改", content.toString(), Long.parseLong(request.getSession().getAttribute("lgid").toString()));
			syslog.setAddtime(new Timestamp(new Date().getTime()));
			syslogServiceImpl.save(syslog);// 添加操作日志
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
	}
	/**
	 * 
	 * 功能描述：根据id重置密码
	 * <P/>
	 * 创建时间：2014年3月20日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param state
	 * @param employee_id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="setPassAction")
	public void setPassAction(HttpServletResponse response, HttpServletRequest request, Long id,Model model)
	{
		List<Integer> list = new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			userServiceImpl.setPass(id);
			Map<String,Object> map=userServiceImpl.findUser(id);
			list.add(1);
			//添加系统操作日志
			StringBuffer content = new StringBuffer();
			content.append("用户：");
			content.append(request.getSession().getAttribute("realname"));
			content.append("，于");
			content.append(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format((new Date().getTime())));
			content.append("修改登录用户");
			content.append(map.get("username")+"("+map.get("realname")+")");
			Syslog syslog = new Syslog(Long.valueOf(request.getSession().getAttribute("lgid").toString()), request.getSession().getAttribute("realname").toString(), request.getSession().getAttribute("companyname").toString(), "修改", "用户修改", content.toString(), Long.parseLong(request.getSession().getAttribute("lgid").toString()));
			syslog.setAddtime(new Timestamp(new Date().getTime()));
			syslogServiceImpl.save(syslog);// 添加操作日志
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
	}


	/**
	 * 
	 * 功能描述:跳转到角色分配页面
	 * <P/>
	 * 创建时间：2013年3月21日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/roleFindListAction")
	public String roleFindListAction(HttpServletRequest request, String[] id, Model model)
	{
		List<Map<String, Object>> list=dictInfoServiceImpl.findListByType("角色类型");
		StringBuffer str=new StringBuffer();
		int d=id.length-1;
		for (int i = 0; i < id.length; i++) {
			str.append(id[i]);
			if(d!=i){
				str.append(",");
			}
		}
		model.addAttribute("list", list);
		model.addAttribute("userid", str);
		return "system/role/roles";
	}
	/**
	 * 
	 * 功能描述:角色分配
	 * <P/>
	 * 创建时间：2013年3月21日
	 * <P/>
	 * 创建人： 段志杨
	 * <P/>
	 * 联系方式： 315874529@qq.com
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/roleGiveAction")
	public String roleGiveAction(HttpServletResponse response,HttpServletRequest request, Long[] id,String userid, Model model)
	{
		List<Integer> list = new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			String[] uid=userid.split(",");
			for (int i = 0; i < uid.length; i++) {
					userServiceImpl.delRid(Long.parseLong(uid[i]));
				
			}
			for (int i = 0; i < uid.length; i++) {
				for (int j = 0; j < id.length; j++) {
					userServiceImpl.addUserRole(Long.parseLong(uid[i]), id[j]);
				}
			}
			list.add(1);
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
		return null;
	}


	/**
	 * 修改密码初始化
	 * @param request
	 * @param model
	 * @return
	 */
	
	@RequestMapping(value="userPassAction0")
	public String userPassAction0(HttpServletRequest request,Long id, Model model)
	{
		model.addAttribute("id", id);
		return "system/user/userSetPass";
	}
	/**
	 * 修改密码
	 * @param request
	 * @param model
	 * @return
	 */
	
	@RequestMapping(value="userPassAction1")
	public void userPassAction1(HttpServletResponse response,HttpServletRequest request,Long id,String pass, Model model)
	{
		List<Integer> list = new ArrayList<Integer>();
		if(request.getSession().getAttribute("realname")==null){
			list.add(0);
		}else if(request.getSession().getAttribute("realname").equals("")){
			list.add(0);
		}else{
			userServiceImpl.setUserPass(id,pass);
			list.add(1);
			//添加系统操作日志
			StringBuffer content = new StringBuffer();
			content.append("用户：");
			content.append(request.getSession().getAttribute("realname"));
			content.append("，于");
			content.append(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format((new Date().getTime())));
			content.append("修改登录密码");
			Syslog syslog = new Syslog(Long.valueOf(request.getSession().getAttribute("lgid").toString()), request.getSession().getAttribute("realname").toString(), request.getSession().getAttribute("companyname").toString(), "修改", "用户修改", content.toString(), Long.parseLong(request.getSession().getAttribute("lgid").toString()));
			syslog.setAddtime(new Timestamp(new Date().getTime()));
			syslogServiceImpl.save(syslog);// 添加操作日志
		}
		response.setCharacterEncoding("utf-8");
		JSONArray array = new JSONArray();
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		array = JSONArray.fromObject(list);
		out.print(array);
	}
}
